package com.example.dormmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dormmanage.dao.IRoomDao;
import com.example.dormmanage.dao.IStudentDao;
import com.example.dormmanage.entity.Room;
import com.example.dormmanage.entity.Student;
import com.example.dormmanage.service.IRoomService;
import com.example.dormmanage.view.ResultView;
import com.example.dormmanage.view.RoomDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RoomService extends ServiceImpl<IRoomDao, Room> implements IRoomService {

    @Autowired
    private IStudentDao studentDao;

    public ResultView<List<RoomDto>> selectRoomList(Integer buildingId) {
        //通过楼宇id查询宿舍列表
        LambdaQueryWrapper<Room> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Room::getBuildingId, buildingId);
        List<Room> roomList = this.list(lqw);
        Set<Integer> floorSet = new HashSet<>();
        //获取楼层列表
        for (int i = 0; i < roomList.size(); i++) {
            floorSet.add(roomList.get(i).getFloor());
        }
        //通过楼层列表去匹配这个楼层的宿舍,然后进行对每一层的数据进行封装
        List<RoomDto> roomDtoList = floorSet.stream().map(item -> {
            RoomDto roomDto = new RoomDto();
            roomDto.setFloor(item + "层");
            //过滤出这次遍历的楼层的宿舍
            List<Room> rooms = roomList.stream().filter(x -> x.getFloor() == item).collect(Collectors.toList());
            roomDto.setRoomList(rooms);
            return roomDto;
        }).collect(Collectors.toList());
        return ResultView.success(roomDtoList);
    }
    //查询宿舍成员列表
    public ResultView<List<Student>> selectRoomMemberList(Integer roomId) {
        LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Student::getRoomId,roomId);
        return ResultView.success(studentDao.selectList(lqw));
    }
}
